package com.manage.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manage.platform.dto.TaskFinalAccountDto;
import com.manage.platform.entity.TaskFinalAccountEntity;
import com.manage.platform.entity.TaskFinalAccountFileEntity;
import com.manage.platform.mapper.TaskFinalAccountMapper;
import com.manage.platform.vo.TaskFinalAccountVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * YWD
 * 2025/11/24
 */
@AllArgsConstructor
@Service
public class TaskFinalAccountServiceImpl extends ServiceImpl<TaskFinalAccountMapper, TaskFinalAccountEntity> {

    private final TaskFinalAccountFileServiceImpl taskFinalAccountFileServiceImpl;

    public TaskFinalAccountVo getByTaskId(Long taskId) {
        return this.baseMapper.getByTaskId(taskId);
    }


    @Transactional(rollbackFor = Exception.class)
    public Boolean addFinalAccount(TaskFinalAccountDto dto) {
        this.baseMapper.addFinalAccount(dto);
        List<TaskFinalAccountFileEntity> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(dto.getFiles())) {
            dto.getFiles().forEach(file -> {
                TaskFinalAccountFileEntity taskFinalAccountFileEntity = new TaskFinalAccountFileEntity();
                taskFinalAccountFileEntity.setTaskFinalAccountId(dto.getId());
                taskFinalAccountFileEntity.setFileUrl(file);
                list.add(taskFinalAccountFileEntity);
            });
            taskFinalAccountFileServiceImpl.saveBatch(list);
        }
        return true;
    }

    public Boolean updateFinalAccount(TaskFinalAccountDto dto) {
        this.updateById(BeanUtil.copyProperties(dto, TaskFinalAccountEntity.class));
        List<TaskFinalAccountFileEntity> list = new ArrayList<>();

        taskFinalAccountFileServiceImpl.removeByTaskFinalAccountId(dto.getId());

        if (CollectionUtil.isNotEmpty(dto.getFiles())) {
            dto.getFiles().forEach(file -> {
                TaskFinalAccountFileEntity taskFinalAccountFileEntity = new TaskFinalAccountFileEntity();
                taskFinalAccountFileEntity.setTaskFinalAccountId(dto.getId());
                taskFinalAccountFileEntity.setFileUrl(file);
                list.add(taskFinalAccountFileEntity);
            });
            taskFinalAccountFileServiceImpl.saveBatch(list);
        }
        return true;
    }


}
